package com.qf.mvc01.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/up")
public class UpLoadController {

    @Value("${fadd}")
    private String filepa;

    @RequestMapping("/test1")
    public String test1(MultipartFile file1, String username,HttpServletRequest request) throws IOException {
        String file11 = request.getParameter("file1");
        System.out.println(file11);
        File file = createFile(file1);
        file1.transferTo(file);
        return "ok";
    }

    private File createFile(MultipartFile file) {
        String prefix = UUID.randomUUID().toString();
        //拿原始文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = prefix + "_" + originalFilename;
        String f = filepa + fileName;
        File file1 = new File(f);
        return file1;
    }

    @RequestMapping("/test2")
    public String test2(MultipartFile file1, HttpServletRequest request) throws IOException {
        ServletContext servletContext = request.getServletContext();

        String realPath = servletContext.getRealPath("/img");
        System.out.println(realPath);
        File file = new File(realPath);
        if (!file.exists()){
            file.mkdirs();
        }
        String string = UUID.randomUUID().toString();
        String originalFilename = file1.getOriginalFilename();
        System.out.println(originalFilename);
        String finalName = string+"_"+originalFilename;
        File file2 = new File(realPath+File.separator+finalName);
        file1.transferTo(file2);
        return "ok";
    }


}
